import { loginApi, userAndEntApi } from '@/api';
import { APPTOKENKEY } from '@/common';
import entLogo from '@/img/entLogo.png';
import { LoginEnt } from '@/models/LoginEnt';
import { useAppSelector } from '@/redux/store';
import { loginEntSlice } from '@/redux/toolkitSlice/LoginEntSlice';
import { loginUserSlice } from '@/redux/toolkitSlice/LoginUserSlice';
import { CaretDownOutlined } from '@ant-design/icons';
import type { DropdownProps } from 'antd';
import { Avatar, Dropdown, Spin } from 'antd';
import classNames from 'classnames';
import type { ReactNode } from 'react';
import { useCallback, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import OStyle from './EntChange.less';

function ListItemMeta({
  avator,
  title,
  description,
  className = '',
  ...props
}: {
  avator?: ReactNode;
  title?: ReactNode;
  description?: ReactNode;
} & React.HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={classNames(OStyle.se_listitem_meta, className)} {...props}>
      <div className={OStyle.meta_avator}>{avator}</div>
      <div className={OStyle.meta_context}>
        <div className={OStyle.meta_title}>{title}</div>
        <div className={OStyle.meta_description}>{description}</div>
      </div>
    </div>
  );
}

function EntChange() {
  const entChangeListBoxRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(false);
  const [dropShow, setDropShow] = useState(false);
  const [entlist, setEntList] = useState<Record<'entName' | 'entTypeName' | 'entId' | 'entLogo', string>[]>([]);
  const loginEnt = useAppSelector((state) => state.loginEnt);

  const { entId: loginEntId } = useAppSelector((state) => state.loginEnt);
  const loginUser = useAppSelector((state) => state.loginUser);
  const dispatch = useDispatch();

  // 选择企业
  const changeEnt = useCallback(
    (entItem: Record<string, any>) => {
      if (loginEntId === entItem.entId) return;
      setLoading(true);
      userAndEntApi
        .safeEduSwitchEnt({ entId: entItem.entId, systemCode: 'logistics_cloud', personId: loginUser.personId })
        .then((res) => {
          if (Number(res.code) === 200) {
            const loginEnt = new LoginEnt({
              ...entItem,
              organizationType: ['government', 'association'].includes(entItem.entTypeCode) ? 1 : 0,
            });
            dispatch(loginEntSlice.actions.updateLoginEnt(loginEnt));
          }
          loginApi
            .getSafeToken(entItem.entId, loginUser.personId)
            .then((tokenRes: any) => {
              localStorage.setItem(APPTOKENKEY, tokenRes.data);
              loginApi
                .getUserRole(entItem.entId, loginUser.personId)
                .then((userRes: any) => {
                  if (userRes.code === '200') {
                    dispatch(loginUserSlice.actions.updateLoginUser({ ...loginUser, loginRole: userRes.data }));
                    setDropShow(false);
                    window.location.href =
                      window.origin + (process.env.processEnvDetail.NODE_ENV === 'production' ? '/safeEduPc/' : '/');
                  }
                })
                .catch((err) => {
                  setLoading(false);
                  console.log('--entChage--getUserRole--err--:', err);
                })
                .finally(() => {
                  setLoading(false);
                });
            })
            .catch((err) => {
              setLoading(false);
              console.log('--entChage--getSafeToken--err--:', err);
            });
        })
        .catch((err) => {
          setLoading(false);
          console.log('--entChage--safeEduSwitchEnt--err--:', err);
        });
    },
    [loginEntId, loginUser.personId],
  );

  const getMenuPanel: DropdownProps['dropdownRender'] = () => (
    <div className={OStyle.ent_change_list_box} ref={entChangeListBoxRef}>
      <p style={{ fontSize: 18, color: '#333' }}>切换企业</p>
      <Spin spinning={loading}>
        <ul className={OStyle.se_listmeta_box}>
          {entlist.map((item) => {
            return (
              <ListItemMeta
                key={item.entId}
                className={item.entId === loginEntId ? OStyle.active : ''}
                onClick={() => {
                  changeEnt(item);
                }}
                avator={
                  <Avatar
                    shape="square"
                    size="large"
                    style={{ marginRight: 12, borderRadius: 8 }}
                    icon={<img src={item.entLogo} />}
                  />
                }
                title={item.entName}
                description={item.entTypeName}
              />
            );
          })}
        </ul>
      </Spin>
    </div>
  );

  // dropDown打开关闭
  const onOpenChange: DropdownProps['onOpenChange'] = (visible) => {
    if (visible) {
      // 重新获取一下企业列表
      setLoading(true);
      userAndEntApi
        .coopEnt({ type: 1 })
        .then((res) => {
          const { data = [] } = res;
          setEntList(
            data.map((v) => {
              return {
                entName: v.name,
                entTypeName: v.entTypeName,
                entId: v.entId,
                entLogo: v.imgPath || entLogo,
                entTypeCode: v.entTypeCode,
              };
            }),
          );
        })
        .finally(() => {
          setLoading(false);
        });
    }
    setTimeout(() => {
      setDropShow(visible);
      if (visible) {
        setTimeout(() => {
          if (entChangeListBoxRef.current) {
            entChangeListBoxRef.current.style.transform = 'translateY(12px)';
          }
        }, 10);
      }
    }, 10);
  };

  return (
    <>
      <Dropdown
        dropdownRender={getMenuPanel}
        trigger={['click']}
        open={dropShow}
        onOpenChange={onOpenChange}
        overlayStyle={{ height: 0 }}
      >
        <div className={OStyle.se_navbar_ent}>
          <Avatar shape="square" size="small" style={{ marginRight: 12 }} icon={<img src={loginEnt.entLogo}></img>} />
          <span style={{ marginRight: 8 }}>{loginEnt.workbenchEntName || loginEnt.entName}</span>
          <CaretDownOutlined
            style={{
              color: 'rgba(255,255,255,.59)',
              transition: 'all .3s ease-in-out',
              transform: `rotateZ(${dropShow ? '180deg' : '0'})`,
            }}
          />
        </div>
      </Dropdown>
    </>
  );
}

export default EntChange;
